package cn.johnyu.controller;

import cn.johnyu.pojo.Book;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;

@RestController
@Tag(name = "BookController", description = "用于图书的增删改查的控制器")
public class BookController {

    @GetMapping("/hello")
    @Operation(summary = "Say Hello", description = "Returns a greeting message")
    @ApiResponse(responseCode = "200", description = "Successfully found user")
    @ApiResponse(responseCode = "404", description = "User not found")
    public String hello(@Parameter(description = "Name of the person to greet", required = true)
                            @RequestParam(name="name") String name) {
        return "Hello, " + name;
    }

    @PostMapping("/books")
    @Operation(summary = "添加一本图书", description = "添加一本图书")
    @ApiResponse(responseCode = "201",
            description = "成功添加",
            content = { @Content(mediaType = "application/json",schema = @Schema(implementation = Book.class)) })
    public Book addBook(@RequestBody(required = true,content = {@Content(mediaType = "application/x-www-form-urlencoded",schema = @Schema(implementation = Book.class))}) Book book) {
        return book;
    }
    @GetMapping("/books/{id}")
    @Operation(summary = "根据ID查询一本书", description = "id是数据库的主键")
    @ApiResponse(responseCode = "200",
            description = "成功查到",
            content = {@Content(mediaType = "application/json",schema = @Schema(implementation = Book.class))})
    @ApiResponse(responseCode = "404", description = "没有查到")
    public ResponseEntity<Book> loadBook(@Parameter(description = "id是数据库的主键", required = true)
                                             @PathVariable("id") Integer id){
        if(id>0){
            Book book=new Book();
            book.setId(id);
            book.setName("book"+id);
            return ResponseEntity.ok(book);
        }else{
            return ResponseEntity.status(404).body(null);
        }

    }

    @GetMapping("/books")
    @Operation(summary = "查询所有图书", description = "查询所有图书")
    @ApiResponse(responseCode = "200",
            description = "成功查到",
            content = {@Content(mediaType = "application/json",schema = @Schema(implementation = Book[].class))})
    public Book[] getBooks() {
        return Book.getBooks();
    }

}